package com.walker.kuyun.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.walker.kuyun.App
import com.walker.kuyun.R
import com.walker.kuyun.bean.*
import com.walker.kuyun.config.Api
import com.walker.kuyun.config.Const.ViewHolderTypeString
import com.walker.kuyun.util.JsoupUtil
import com.walker.kuyun.util.ParseHtmlUtil.parseBotit
import com.walker.kuyun.util.ParseHtmlUtil.parseDtit
import com.walker.kuyun.util.ParseHtmlUtil.parseImg
import com.walker.kuyun.util.ParseHtmlUtil.parseMovurls
import com.walker.kuyun.util.Util.showToastOnThread
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.jsoup.nodes.Document
import org.jsoup.select.Elements


class TMDetailViewModel : ViewModel() {
    var cover: ImageBean = ImageBean("", "", "", "")
    var title: String = ""
    var TMDetailList: MutableList<TMDetailBean> = ArrayList()
    var mldVideoDetailList: MutableLiveData<Boolean> = MutableLiveData()
    private val linkMap = HashMap<String, String>()
    private fun getKVMap(document: Document) {
        linkMap.clear()
        val select: Elements =
            document.getElementsByClass("fed-drop-btns fed-padding fed-col-xs3 fed-col-md2")
                .select("a")
        for (element in select) {
            var href = element.attr("href")
            href = href.substring(0, href.lastIndexOf("/"))
            linkMap[href] = element.text()
        }
    }

    //根据前半部分划分存储
    private fun getTextByHref(document: Document, key: String): String {
        if (linkMap.size <= 0) getKVMap(document)
        return linkMap[key.substring(0, key.lastIndexOf("/"))]!!
    }

    fun getAnimeDetailData(partUrl: String) {
        TMDetailList.clear()

        viewModelScope.launch(Dispatchers.IO) {
            try {
                val url = Api.MAIN_URL + partUrl
                val document = JsoupUtil.getDocument(url)
                getKVMap(document)
                cover.url = document.getElementsByClass("fed-list-pics fed-lazy fed-part-2by3")
                    .attr("data-original")
                    .let {
                        if (it.startsWith("http")) it
                        else Api.MAIN_URL + it
                    }
                title =
                    document.getElementsByClass("fed-tabs-info  fed-rage-foot fed-part-rows fed-part-layout fed-back-whits fed-play-data")
                        .attr("data-name")
                val items =
                    document.getElementsByClass("fed-padding fed-col-xs6 fed-col-sm4 fed-col-md3 fed-col-lg2")
                val items2 =
                    document.getElementsByClass("fed-padding fed-col-xs3 fed-col-md2 fed-col-lg1")//epoise

                for (mutableEntry in linkMap) {
                    val linkKey = mutableEntry.key
                    val linkValue = mutableEntry.value
                    TMDetailList.add(
                        TMDetailBean(
                            ViewHolderTypeString.HEADER_1, "",
                            linkValue,
                            "",
                            null
                        )
                    )
                    val itemList = java.util.ArrayList<TMEpisodeDataBean>()
                    val finalItems =
                        when {
                            items.size > 0 -> items
                            items2.size > 0 -> items2
                            else -> throw RuntimeException(
                                "AnimeDetailViewModel get error data!"
                            )
                        }
                    for (element in finalItems) {
                        val sHref = element.select("a").attr("href")
                        val sText = element.select("a").text()
                        if (!sHref.startsWith(linkKey)) continue
                        itemList.add(
                            TMEpisodeDataBean(
                                ViewHolderTypeString.ITEM_EPISODE_2,
                                sHref,
                                sText
                            )
                        )
                    }
                    TMDetailList.add(
                        TMDetailBean(
                            ViewHolderTypeString.HORIZONTAL_LIST_1,
                            "",
                            "",
                            "",
                            itemList
                        )
                    )
                }
                TMDetailList.add(
                    TMDetailBean(
                        ViewHolderTypeString.HEADER_1, "",
                        "剧情简介",
                        "",
                        null
                    )
                )
                TMDetailList.add(
                    TMDetailBean(
                        ViewHolderTypeString.ITEM_DESCRIBE_1, "",
                        "",
                        document.getElementsByClass("fed-padding fed-part-both fed-text-muted")
                            .text(),
                        null
                    )
                )

                val infoList = document.select("dd ul.fed-part-rows li")
                val animeInfoBean = TMInfoBean(
                    "",
                    "",
                    title,
                    ImageBean("", "", cover.url, url),
                    "",
                    infoList[3].select("a").text(),
                    infoList[4].select("a").text(),
                    "index",
                    arrayListOf(
                        VideoTypeBean(
                            "",
                            "",
                            "",
                            infoList[2].select("a").text()// 描述
                        )
                    ),
                    arrayListOf(),
                    "-"
                )
                TMDetailList.add(
                    0,
                    TMDetailBean(
                        ViewHolderTypeString.ITEM_INFO_1, "",
                        "",
                        "",
                        headerInfo = animeInfoBean
                    )
                )
                mldVideoDetailList.postValue(true)
                if (true) return@launch
                TMDetailList.clear()
                //番剧头部信息
                val area: Elements = document.getElementsByClass("area")
                for (i in area.indices) {
                    val areaChildren = area[i].children()
                    for (j in areaChildren.indices) {
                        when (areaChildren[j].className()) {
                            "fire l" -> {
                                var alias = ""
                                var info = ""
                                var year = ""
                                var index = ""
                                var animeArea = ""
                                val videoType: MutableList<VideoTypeBean> = ArrayList()
                                val tag: MutableList<VideoTypeBean> = ArrayList()

                                val fireLChildren =
                                    areaChildren[j].select("[class=fire l]")[0].children()
                                for (k in fireLChildren.indices) {
                                    when (fireLChildren[k].className()) {
                                        "thumb l" -> {
                                            cover.url = fireLChildren[k]
                                                .select("img").attr("src")
                                            cover.referer = url
                                        }
                                        "rate r" -> {
                                            val rateR = fireLChildren[k]
                                            title = rateR.select("h1").text()
                                            val sinfo: Elements = rateR.select("[class=sinfo]")
                                            val span: Elements = sinfo.select("span")
                                            val p: Elements = sinfo.select("p")
                                            if (p.size == 1) {
                                                alias = p[0].text()
                                            } else if (p.size == 2) {
                                                alias = p[0].text()
                                                info = p[1].text()
                                            }
                                            year = span[0].text()
                                            animeArea = span[1].select("a").text()
                                            index = span[3].select("a").text()
                                            val typeElements: Elements = span[2].select("a")
                                            for (l in typeElements.indices) {
                                                videoType.add(
                                                    VideoTypeBean(
                                                        "",
                                                        typeElements[l].attr("href"),
                                                        Api.MAIN_URL + typeElements[l].attr("href"),
                                                        typeElements[l].text()
                                                    )
                                                )
                                            }
                                            val tagElements: Elements = span[4].select("a")
                                            for (l in tagElements.indices) {
                                                tag.add(
                                                    VideoTypeBean(
                                                        "",
                                                        tagElements[l].attr("href"),
                                                        Api.MAIN_URL + tagElements[l].attr("href"),
                                                        tagElements[l].text()
                                                    )
                                                )
                                            }
                                        }
                                        "tabs" -> {     //播放列表+header
                                            TMDetailList.add(
                                                TMDetailBean(
                                                    ViewHolderTypeString.HEADER_1, "",
                                                    fireLChildren[k].select("[class=tabs]")
                                                        .select("[class=menu0]")
                                                        .select("li").text(),
                                                    "",
                                                    null
                                                )
                                            )

                                            TMDetailList.add(
                                                TMDetailBean(
                                                    ViewHolderTypeString.HORIZONTAL_LIST_1,
                                                    "",
                                                    "",
                                                    "",
                                                    parseMovurls(
                                                        fireLChildren[k]
                                                            .select("[class=main0]")
                                                            .select("[class=movurl]")[0]
                                                    )
                                                )
                                            )
                                        }
                                        "botit" -> {     //其它header
                                            TMDetailList.add(
                                                TMDetailBean(
                                                    ViewHolderTypeString.HEADER_1, "",
                                                    parseBotit(fireLChildren[k]),
                                                    "",
                                                    null
                                                )
                                            )
                                        }
                                        "dtit" -> {     //其它header
                                            TMDetailList.add(
                                                TMDetailBean(
                                                    ViewHolderTypeString.HEADER_1, "",
                                                    parseDtit(fireLChildren[k]),
                                                    "",
                                                    null
                                                )
                                            )
                                        }
                                        "info" -> {         //动漫介绍
                                            TMDetailList.add(
                                                TMDetailBean(
                                                    ViewHolderTypeString.ITEM_DESCRIBE_1, "",
                                                    "",
                                                    fireLChildren[k]
                                                        .select("[class=info]").text(),
                                                    null
                                                )
                                            )
                                        }
                                        "img" -> {         //系列动漫推荐
                                            TMDetailList.add(
                                                TMDetailBean(
                                                    ViewHolderTypeString.GRID_LIST_1,
                                                    "",
                                                    "",
                                                    "",
                                                    null,
                                                    parseImg(fireLChildren[k], url)
                                                )
                                            )
                                        }
                                    }
                                }
                                val animeInfoBean = TMInfoBean(
                                    "",
                                    "",
                                    title,
                                    ImageBean("", "", cover.url, url),
                                    alias,
                                    animeArea,
                                    year,
                                    index,
                                    videoType,
                                    tag,
                                    info
                                )
                                TMDetailList.add(
                                    0,
                                    TMDetailBean(
                                        ViewHolderTypeString.ITEM_INFO_1, "",
                                        "",
                                        "",
                                        headerInfo = animeInfoBean
                                    )
                                )
                            }
                        }
                    }
                }
                mldVideoDetailList.postValue(true)
            } catch (e: Exception) {
                TMDetailList.clear()
                mldVideoDetailList.postValue(false)
                e.printStackTrace()
                (App.getApp()
                    .getString(R.string.get_data_failed) + "\n" + e.message).showToastOnThread()
            }
        }
    }

    companion object {
        const val TAG = "AnimeDetailViewModel"
    }
}